package com.wwg.warehouse.usecase

import com.google.gson.Gson
import com.wwg.warehouse.entities.CommonResponse
import com.wwg.warehouse.entities.SyncBean
import com.wwg.warehouse.utils.fromJsonObject
import splitties.init.appCtx
import java.io.File
import java.io.FileReader

class ServerSyncParser {

    fun loadAsserts(): CommonResponse<SyncBean> {
        val json = String(appCtx.assets.open(PULL_DATA_FILE).readBytes())
        println("json read complete ${json.length}")
        return Gson().fromJsonObject<CommonResponse<SyncBean>>(json) ?: CommonResponse()
    }

    /*异常处理暂不涉及
    @Throws(IOException::class)
    fun loadFile(): SyncBean {
        val file = File(appCtx.externalCacheDir, PULL_DATA_FILE)
        if (file.exists()) {
            var reader: FileReader? = null
            try {
                reader = FileReader(file)
                val content = reader.readText()
                return Gson().fromJson(content, SyncBean::class.java)
            } finally {
                reader?.close()
            }
        }

        throw IOException("file $PULL_DATA_FILE on path ${appCtx.externalCacheDir} not exists")
    }
    */

    //异常处理暂不涉及
    fun loadFile(): SyncBean {
        val file = File(appCtx.externalCacheDir, PULL_DATA_FILE)
        if (file.exists()) {
            var reader: FileReader? = null
            try {
                reader = FileReader(file)
                val content = reader.readText()
                return Gson().fromJson(content, SyncBean::class.java)
            } finally {
                reader?.close()
            }
        }

        return SyncBean()
    }

    companion object {
        private const val PULL_DATA_FILE = "pull_data.json"
    }
}